package cn.wowjoy.office.pm.view.fragment.report;


import android.app.Fragment;
import android.arch.lifecycle.Observer;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;

import com.github.jdsjlzx.interfaces.OnRefreshListener;
import com.google.gson.Gson;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.Serializable;
import java.util.List;

import javax.inject.Inject;

import cn.wowjoy.office.R;
import cn.wowjoy.office.baselivedata.appbase.LiveDataWrapper;
import cn.wowjoy.office.baselivedata.appbase.NewBaseFragment;
import cn.wowjoy.office.common.decoration.SimpleItemDecoration;
import cn.wowjoy.office.common.widget.CommonDialog;
import cn.wowjoy.office.data.constant.Constants;
import cn.wowjoy.office.data.event.RedPointEventReport;
import cn.wowjoy.office.databinding.FragmentRallBinding;
import cn.wowjoy.office.homepage.MenuHelper;
import cn.wowjoy.office.pm.data.PmReportDetailResponse;
import cn.wowjoy.office.pm.data.PmReportIndexResponse;
import cn.wowjoy.office.pm.data.SubmitResponse;
import cn.wowjoy.office.pm.db.PmListDao;
import cn.wowjoy.office.pm.db.PmReportListDetailEntity;
import cn.wowjoy.office.pm.db.PmReportListEntity;
import cn.wowjoy.office.pm.view.PmReportDetailActivity;
import cn.wowjoy.office.pm.view.SignNameActivity;
import cn.wowjoy.office.pm.view.viewodel.PmReportViewModel;
import cn.wowjoy.office.utils.ToastUtil;
import cn.wowjoy.office.utils.dialog.DialogUtils;
import cn.wowjoy.office.utils.dialog.MDialog;

/**
 * A simple {@link Fragment} subclass.
 */
public class RAllFragment extends NewBaseFragment<FragmentRallBinding, PmReportViewModel> implements View.OnClickListener {
    @Inject
    PmListDao mPmListDao;
    private MDialog waitDialog;
    private String status;
    private int state;

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @return A new instance of fragment StayOutStockFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static RAllFragment newInstance(String status) {
        RAllFragment fragment = new RAllFragment();
        Bundle args = new Bundle();
        args.putString("status", status);
        fragment.setArguments(args);
        return fragment;
    }

    public RAllFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            status = getArguments().getString("status");
        }
        viewModel.setStatus(status);
    }

    @Override
    protected Class<PmReportViewModel> getViewModel() {
        return PmReportViewModel.class;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_rall;
    }

    @Override
    protected void onCreateViewLazy(Bundle savedInstanceState) {
        binding.setViewModel(viewModel);
        binding.rvFragment.setLayoutManager(new LinearLayoutManager(getActivity()));
        switch (status) {
            case "80-0": //全部   待完善+未确认
                binding.rvFragment.setAdapter(viewModel.allAdapter);
                status ="";
                state = Constants.EDIT_REPORT;
                break;
            case "80-4":
                binding.rvFragment.setAdapter(viewModel.yetAdapter);
                binding.rvFragment.setLoadMoreEnabled(false);
                state = Constants.EDIT_REPORT;
                break;
            case "80-3":
                binding.rvFragment.setAdapter(viewModel.noAdapter);
                state = Constants.EDIT_REPORT;
                break;
            case "80-1,80-2":
                binding.rvFragment.setAdapter(viewModel.yesAdapter);
                state = Constants.LOOK_REPORT;
                break;
        }

        binding.rvFragment.addItemDecoration(new SimpleItemDecoration(getContext(), SimpleItemDecoration.VERTICAL_LIST));
        binding.emptyView.emptyContent.setText("暂无数据");
        binding.rvFragment.setEmptyView(binding.emptyView.getRoot());
        binding.emptyView.emptyContent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                response();
            }
        });
        binding.rvFragment.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh() {
                //下拉刷新 请求服务器新数据
                response();
            }
        });
        binding.cancel.setOnClickListener(this);
        binding.confirm.setOnClickListener(this);
        initView();
        initObserve();

    }

    private void initView() {
    }

    private void response(){
        if(!status.equals("80-4")){
            viewModel.getAllListInfo(true, "", status);
        }else{
            //读取数据库数据
            viewModel.queryYetData(true,viewModel.userInfo.getStaffName() );
        }
    }
    private CommonDialog noticeSaveDialog;
    public void noticeDelete(String ids,String qrCode,String userName) {
        noticeSaveDialog = new CommonDialog.Builder()
                .setTitle("提醒")
                .setContent("是否要删除该PM报告？")
                .setCancelBtn("否", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        noticeSaveDialog.dismiss();
                    }
                })
                .setConfirmBtn("是", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        noticeSaveDialog.dismiss();
                        if(TextUtils.isEmpty(qrCode)){
                            viewModel.deletePmReport(ids, MenuHelper.getAuidS().get("zc_pm"));
                        }else{
                            viewModel.deleteLocal(qrCode,userName);
                        }

                    }
                })
                .create();
        noticeSaveDialog.show(getFragmentManager(), null);
    }
    private void initObserve() {
        //远程库删除(未确认)
        viewModel.deleteNotice.observe(this, new Observer<String>() {
            @Override
            public void onChanged(@Nullable String s) {
               if(!TextUtils.isEmpty(s)){
                   noticeDelete(s,"","");
               }
            }
        });
        viewModel.delete.observe(this, new Observer<LiveDataWrapper<SubmitResponse>>() {
            @Override
            public void onChanged(@Nullable LiveDataWrapper<SubmitResponse> stringLiveDataWrapper) {
                switch (stringLiveDataWrapper.status) {
                    case LOADING:
                        waitDialog = DialogUtils.waitingDialog(getActivity());
                        break;
                    case SUCCESS:
                        DialogUtils.dismiss(getActivity());
                        ToastUtil.toastImage(getActivity(),"删除成功",-1);
//                        response();
                        break;
                    case ERROR:
                        DialogUtils.dismiss(getActivity());
                        handleException(stringLiveDataWrapper.error, false);
                        break;
                }

            }
        });
        viewModel.dleteLocalDataNotice.observe(this, new Observer<PmReportListEntity>() {
            @Override
            public void onChanged(@Nullable PmReportListEntity pmReportListEntity) {
                if(null != pmReportListEntity && !TextUtils.isEmpty(pmReportListEntity.getQrCode()) && !TextUtils.isEmpty(pmReportListEntity.getUserName())){
                    noticeDelete("",pmReportListEntity.getQrCode(),pmReportListEntity.getUserName());
                }
            }
        });
        //数据库删除（未完善）
        viewModel.dleteLocalData.observe(this, new Observer<LiveDataWrapper<Boolean>>() {
            @Override
            public void onChanged(@Nullable LiveDataWrapper<Boolean> booleanLiveDataWrapper) {
                switch (booleanLiveDataWrapper.status) {
                    case LOADING:
                        waitDialog = DialogUtils.waitingDialog(getActivity());
                        break;
                    case SUCCESS:
                        DialogUtils.dismiss(getActivity());
                        if(booleanLiveDataWrapper.data.booleanValue()){
                            ToastUtil.toastImage(getActivity(),"删除成功",-1);
                        }
                        response();
                        break;
                    case ERROR:
                        DialogUtils.dismiss(getActivity());
                        handleException(booleanLiveDataWrapper.error, false);
                        break;
                }

            }
        });
        viewModel.clickItem.observe(this, new Observer<PmReportListEntity>() {
            @Override
            public void onChanged(@Nullable PmReportListEntity pmReportIndexDetail) {
                if(null != pmReportIndexDetail){
                    viewModel.getPmReport(pmReportIndexDetail.getId()+"");
                }
            }
        });
        //本地数据库列表数据（未完善）
        viewModel.localSave.observe(this, new Observer<LiveDataWrapper<List<PmReportListEntity>>>() {
            @Override
            public void onChanged(@Nullable LiveDataWrapper<List<PmReportListEntity>> listLiveDataWrapper) {
                switch (listLiveDataWrapper.status) {
                    case LOADING:
                        waitDialog = DialogUtils.waitingDialog(getActivity());
                        break;
                    case SUCCESS:
                        DialogUtils.dismiss(getActivity());
                        if(null != viewModel.yet_list && !viewModel.yet_list.isEmpty() ){
                            EventBus.getDefault().post(new RedPointEventReport(viewModel.yet_list.size(),status));
                        }else{
                            EventBus.getDefault().post(new RedPointEventReport(0,status));
                        }
                        break;
                    case ERROR:
                        DialogUtils.dismiss(getActivity());
                        handleException(listLiveDataWrapper.error, true);
                        break;
                }
            }
        });
        //本地数据库列表点击（未完善）
        viewModel.localData.observe(this, new Observer<LiveDataWrapper<PmReportListDetailEntity>>() {
            @Override
            public void onChanged(@Nullable LiveDataWrapper<PmReportListDetailEntity> pmReportListDetailEntityLiveDataWrapper) {
                switch (pmReportListDetailEntityLiveDataWrapper.status) {
                    case LOADING:
                       DialogUtils.waitingDialog(getActivity());
                        break;
                    case SUCCESS:
                        DialogUtils.dismiss(getActivity());
                        if (null != pmReportListDetailEntityLiveDataWrapper.data) {
                            PmReportListDetailEntity p = pmReportListDetailEntityLiveDataWrapper.data;
                            PmReportDetailResponse pmReportDetailResponse = new Gson().fromJson(p.getJsonEntity(), PmReportDetailResponse.class);
                            PmReportDetailActivity.launch(getActivity(), state, pmReportDetailResponse.getPmReportVO().getQrCode(),pmReportDetailResponse,true);
                        }
                        break;
                    case ERROR:
                        DialogUtils.dismiss(getActivity());
                        handleException(pmReportListDetailEntityLiveDataWrapper.error, false);
                        break;
                }
            }
        });
        //网络请求得数据
        viewModel.detail.observe(this, new Observer<LiveDataWrapper<PmReportDetailResponse>>() {
            @Override
            public void onChanged(@Nullable LiveDataWrapper<PmReportDetailResponse> pmReportDetailResponseLiveDataWrapper) {
                switch (pmReportDetailResponseLiveDataWrapper.status) {
                    case LOADING:
                        waitDialog = DialogUtils.waitingDialog(getActivity());
                        break;
                    case SUCCESS:
                        DialogUtils.dismiss(getActivity());
                        if (null != pmReportDetailResponseLiveDataWrapper.data) {
                            if(pmReportDetailResponseLiveDataWrapper.data.getPmReportVO().getBillStatus().equals("80-1") || pmReportDetailResponseLiveDataWrapper.data.getPmReportVO().getBillStatus().equals("80-2")){
                                PmReportDetailActivity.launch(getActivity(), 3, pmReportDetailResponseLiveDataWrapper.data.getPmReportVO().getQrCode(),pmReportDetailResponseLiveDataWrapper.data,false);
                            }else{
                                PmReportDetailActivity.launch(getActivity(), state, pmReportDetailResponseLiveDataWrapper.data.getPmReportVO().getQrCode(),pmReportDetailResponseLiveDataWrapper.data,false);
                            }
                        }
                        break;
                    case ERROR:
                        DialogUtils.dismiss(getActivity());
                        handleException(pmReportDetailResponseLiveDataWrapper.error, false);
                        break;
                }
            }
        });
        //网络请求得所有数据（未完成和已完成）
        viewModel.allData.observe(this, new Observer<LiveDataWrapper<PmReportIndexResponse>>() {
            @Override
            public void onChanged(@Nullable LiveDataWrapper<PmReportIndexResponse> inspectionTotalResponseLiveDataWrapper) {
                switch (inspectionTotalResponseLiveDataWrapper.status) {
                    case LOADING:
                        DialogUtils.waitingDialog(getActivity());
                        break;
                    case SUCCESS:
                        DialogUtils.dismiss(getActivity());
                        if(status.equals("80-1,80-2")){
                            if(null != viewModel.yes_list && !viewModel.yes_list.isEmpty() ){
                                EventBus.getDefault().post(new RedPointEventReport(viewModel.yes_list.size(),status));
                            }else{
                                EventBus.getDefault().post(new RedPointEventReport(0,status));
                            }
                        }else if(status.equals("80-3")){
                            if(null != viewModel.no_list && !viewModel.no_list.isEmpty() ){
                                EventBus.getDefault().post(new RedPointEventReport(viewModel.no_list.size(),status));
                            }else{
                                EventBus.getDefault().post(new RedPointEventReport(0,status));
                            }
                        }else{
                            if(null != viewModel.all_list && !viewModel.all_list.isEmpty() ){
                                EventBus.getDefault().post(new RedPointEventReport(viewModel.all_list.size(),status));
                            }else{
                                EventBus.getDefault().post(new RedPointEventReport(0,status));
                            }
                        }
                        break;
                    case ERROR:
                        DialogUtils.dismiss(getActivity());
                        binding.rvFragment.refreshComplete(1);
                        handleException(inspectionTotalResponseLiveDataWrapper.error, false);
                        break;
                }
            }
        });
        viewModel.bottomShow.observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(@Nullable Boolean state) {
                if (null != state && state) {
                    binding.bottom.setVisibility(View.VISIBLE);
                    binding.rvFragment.setPullRefreshEnabled(false);
                    binding.rvFragment.setLoadMoreEnabled(false);
                }
            }
        });
        viewModel.selectNum.observe(this, new Observer<Integer>() {
            @Override
            public void onChanged(@Nullable Integer state) {
                binding.tvAlreadySelect.setText(state + "");
            }
        });
    }
    @Override
    protected void onResumeLazy() {
        super.onResumeLazy();
        response();
        viewModel.nolinnerAdapter.showAll(false, false);
        binding.bottom.setVisibility(View.GONE);
        binding.tvAlreadySelect.setText("0");
        binding.rvFragment.setPullRefreshEnabled(true);
        binding.rvFragment.setLoadMoreEnabled(true);
    }

    @Override
    protected ViewGroup getErrorViewRoot() {
        return binding.flError;
    }

    @Override
    protected void refreshError() {
        super.refreshError();
        response();
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(RedPointEventReport event) {

    }
    @Override
    protected void onStartLazy() {
        super.onStartLazy();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    @Override
    protected void onDestroyViewLazy() {
        super.onDestroyViewLazy();
        EventBus.getDefault().unregister(this);
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.cancel:
                viewModel.nolinnerAdapter.showAll(false, false);
                binding.bottom.setVisibility(View.GONE);
                binding.tvAlreadySelect.setText("0");

                binding.rvFragment.setPullRefreshEnabled(true);
                binding.rvFragment.setLoadMoreEnabled(true);
                break;
            case R.id.confirm:
                if(viewModel.nolinnerAdapter.getSelectList().size()>0){
                    Intent intent = new Intent(getActivity(), SignNameActivity.class);
                    intent.putExtra("select", (Serializable) viewModel.nolinnerAdapter.getSelectList());
                    startActivity(intent);
                    viewModel.nolinnerAdapter.showAll(false, false);
                    binding.bottom.setVisibility(View.GONE);
                    binding.tvAlreadySelect.setText("0");

                    binding.rvFragment.setPullRefreshEnabled(true);
                    binding.rvFragment.setLoadMoreEnabled(true);
                }else{
                    ToastUtil.toastWarning(getActivity(),"还未选择",R.mipmap.noselect,true);
                }
                break;
        }

    }
}
